import React, { Component } from 'react';
import axios from 'axios'
import ListItem from './ListItem'
import ToggleDemo from './ToggleDemo'

import { CSSTransition, TransitionGroup } from 'react-transition-group'

class App extends Component {
  constructor(props) {
    super(props);

    this.ulElement = React.createRef();
    this.state = {
      text: 'mongod',
      list: [] //['frps', 'sshd', 'pm2', 'vnc-server', 'aria2' ]
    }
  }

  componentDidMount() {
    axios.get('http://rap2api.taobao.org/app/mock/data/1343186').then(res => {
      console.log('获取数据成功', res)
      this.setState({
        list: res.data.list
      })
    }).catch(e => {
      console.log('Error', e);
    })
  }

  handleInputChange = (el) => {
    // const nv = el.target.value
    const nv = this.inputEl.value // 这里只是为了演示 ref 的用法
    this.setState({
      text: nv
    })
  }

  addService = () => {
    const text = this.state.text
    if (text) {
      this.setState({
        list: [...this.state.list, text],
        text: ''
      }, () => {
        console.log('操作完成', this.ulElement.current)
      })
    }

  }

  handleRemoveItem = (index) => {
    let list = this.state.list // 不能直接操作state中的数据！
    list.splice(index, 1)

    this.setState({
      list: list
    })
  }

  render() {
    return (
      <React.Fragment>
        <div>
          {/* 在JSX中写注释 */}
          <div>
            <label htmlFor="myInput">增加服务</label>
            <input
              ref={(el) => {
                this.inputEl = el
              }}
              id="myInput"
              className="input"
              onChange={this.handleInputChange}
              value={this.state.text}
            />
            <button onClick={this.addService}>增加</button>
          </div>

          <ul ref={this.ulElement}>
            <TransitionGroup>
              {
                this.state.list.map((v, i) => {
                  return (
                    <CSSTransition
                      timeout={500}
                      classNames='fade'
                      unmountOnExit={true}
                      appear={true}
                      key={v+i}
                    >
                      <ListItem

                        content={v}
                        index={i}
                        key={v + i}
                        handleClick={this.handleRemoveItem}
                      >
                      </ListItem>
                    </CSSTransition>
                  )
                })
              }
            </TransitionGroup>
          </ul>

          <p>一共有 <span>{this.state.list.length}</span> 个服务</p>
        </div>

        <ToggleDemo />
      </React.Fragment>
    );
  }
}

export default App;
